const route = require('koa-router')();
const User = require('../../model/user/user.js')

route.post('/register',async(ctx,next)=>{
    let data = ctx.request.body
    if(!(/^1[3456789]\d{9}$/.test(data.mobile))){
        ctx.body = {
            code:400,
            msg:'手机号码格式错误'
        }
    }else if(!(/^[\w]{6,12}$/.test(data.password))){
        ctx.body = {
            code:400,
            msg:'请输入6-12位数密码'
        }
    }else{
        let findinfo = await User.find({mobile:data.mobile})
        if(findinfo.length!=0){
            ctx.body = {
                code:400,
                msg:'该手机号码已注册',
            }
        }else{
            // data.user_id = user_id+=1
            let all = await User.find()
            if(all.length==0){//如果在添加时没有用户
                data.user_id = 100000//第一位用户初始化userid为100000
            }else{//如果有用户
                data.user_id = all[all.length-1].user_id+1//取数据库用户表中最后一位用户userid，然后+1
            }
            await User.create(data)
            ctx.body = {
                code:200,
                msg:'ok'
            }
        }
    }
})

module.exports = route